package com.jumeng.server.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jumeng.entity.WxUserEntity;
import com.jumeng.server.AuthLoginService;
import com.jumeng.server.WxUserService;
import com.jumeng.util.ShaUtil;
import com.jumeng.util.WxUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class AuthLoginServiceImpl implements AuthLoginService {

    @Value("${wx.token}")
    public String token;

    @Value("${wx.appsecret}")
    public String appsecret;

    @Value("${wx.Appid}")
    public String appid;

    @Value("${wx.redirectUrl}")
    public String redirectUrl;

    @Autowired
    private WxUserService wxUserService;

    @Override
    public String checkSignature(String signature, String timestamp, String nonce, String echostr) {
        // 1.将token、timestamp、nonce三个参数进行字典序排序
        String tmpStr = ShaUtil.getSHA1(token, timestamp, nonce);
        log.error("比较字符{},{}", tmpStr, signature.toUpperCase());
        //TODO 进行对比
        if (tmpStr.equals(signature.toUpperCase())) {
            return echostr;
        }
        return echostr;
    }

    @Override
    public String receiveAccessToken(String appid, String appsecret) {
        String resStr = WxUtils.getReceiveAccessToken(appid, appsecret);
        JSONObject jsonObject = JSON.parseObject(resStr);
        // accessToken
        String accessToken = (String) jsonObject.get("access_token");
        // token过期时间
        Integer expiresIn = (Integer) jsonObject.get("expires_in");
        return accessToken;
    }

    @Override
    public void oauth2Authorize() {
        WxUtils.oauth2Authorize(appid, redirectUrl);
    }

    @Override
    public String receiveOpenId(String code) {
        String resStr = WxUtils.receiveOpenId(appid, appsecret, code);
        WxUserEntity wxUserEntity = JSON.parseObject(resStr, WxUserEntity.class);
        // 保存用户信息
        wxUserService.save(wxUserEntity);
        return wxUserEntity.getOpenId();
    }
}
